package site.xuxingcan.autologin;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.FileInputStream;

/**
 * Created by xuxingcan on 2016/9/6.
 */
public class FloatUtil {
    private Context mContext;
    private WindowManager.LayoutParams wmParams;
    private WindowManager mWindowManager;
    private LinearLayout mFloatLayout;
    private View homeButton;
    private View loginButton;
    private Gson gson;
    private Handler mHandler;
    private boolean isRunning = false;
    private boolean isVer = false;
    private static Point QQLoginButtonPoint;
    private static Point QQLoginActivityUserPoint;
    private static Point QQLoginActivityPWDPoint;
    private static Point QQLoginActivityLoginPoint;
    private static Point QQCodeActivityCodeStartPoint;
    private static Point QQCodeActivityCodeEndPoint;
    private static Point QQCodeActivityEditPoint;

    private static Point QQCodeActivityFinishPoint;
    private static Point WXLoginButtonPoint;
    private static Point WXPhoneLoginActivityUseOtherPoint;
    private static Point WXPhoneLoginActivityUserPoint;
    private static Point WXPhoneLoginActivityPWDPoint;
    private static Point WXPhoneLoginActivityLoginPoint;
    private static Point WXOtherLoginActivityUserPoint;
    private static Point WXOtherLoginActivityPWDPoint;
    private static Point WXOtherLoginActivityLoginPoint;

//    static {
//        //魅蓝note2
//        QQLoginButtonPoint = new Point(300, 1690);
//        QQLoginActivityUserPoint = new Point(540, 600);
//        QQLoginActivityPWDPoint = new Point(540, 720);
//        QQLoginActivityLoginPoint = new Point(540, 900);
//        QQCodeActivityCodeStartPoint = new Point(340, 260);
//        QQCodeActivityCodeEndPoint = new Point(735, 420);
//        QQCodeActivityEditPoint = new Point(600, 650);
//        QQCodeActivityFinishPoint = new Point(1000, 150);
//
//        WXLoginButtonPoint = new Point(290, 1790);
//        WXPhoneLoginActivityUseOtherPoint = new Point(750, 1780);
//
//        WXPhoneLoginActivityUserPoint = new Point(550, 500);
//        WXPhoneLoginActivityPWDPoint = new Point(550, 620);
//        WXPhoneLoginActivityLoginPoint = new Point(550, 860);
//
//        WXOtherLoginActivityUserPoint = new Point(550, 320);
//        WXOtherLoginActivityPWDPoint = new Point(550, 460);
//        WXOtherLoginActivityLoginPoint = new Point(550, 690);
//    }

    static {
        //coolpad
        QQLoginButtonPoint = new Point(160, 840);
        QQLoginActivityUserPoint = new Point(270, 344);
        QQLoginActivityPWDPoint = new Point(270, 407);
        QQLoginActivityLoginPoint = new Point(270, 484);
        QQCodeActivityCodeStartPoint = new Point(155, 130);
        QQCodeActivityCodeEndPoint = new Point(355, 215);
        QQCodeActivityEditPoint = new Point(192, 316);
        QQCodeActivityFinishPoint = new Point(514, 66);

        WXLoginButtonPoint = new Point(144, 885);
        WXPhoneLoginActivityUseOtherPoint = new Point(400, 900);

        WXPhoneLoginActivityUserPoint = new Point(350, 250);
        WXPhoneLoginActivityPWDPoint = new Point(350, 308);
        WXPhoneLoginActivityLoginPoint = new Point(350, 416);

        WXOtherLoginActivityUserPoint = new Point(365, 165);
        WXOtherLoginActivityPWDPoint = new Point(365, 243);
        WXOtherLoginActivityLoginPoint = new Point(365, 346);
    }

    public void createFloatView(final Context mContext) {
        this.mContext = mContext;
        mHandler = new Handler(Looper.getMainLooper());
        gson = new Gson();
        wmParams = new WindowManager.LayoutParams();
        //获取的是WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager) mContext.getSystemService(mContext.WINDOW_SERVICE);
        //设置window type
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        //设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //调整悬浮窗显示的停靠位置为左侧置顶
        wmParams.gravity = Gravity.LEFT | Gravity.TOP;
        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
        wmParams.x = mWindowManager.getDefaultDisplay().getWidth();
        wmParams.y = 150;

        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

		 /*// 设置悬浮窗口长宽数据
        wmParams.width = 200;
        wmParams.height = 80;*/

        //获取浮动窗口视图所在布局
        mFloatLayout = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.float_layout, null);
        //添加mFloatLayout
        homeButton = mFloatLayout.findViewById(R.id.home);
        loginButton = mFloatLayout.findViewById(R.id.login);
        homeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isRunning) {
                    Toast("登陆程序运行中，请稍后！");
                    return;
                }
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(intent);
            }
        });
        loginButton.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if (SharedPreferenceUtil.getInstance().getIsMove()) {
                    //getRawX是触摸位置相对于屏幕的坐标，getX是相对于按钮的坐标
                    wmParams.x = (int) event.getRawX() - loginButton.getMeasuredWidth() / 2;
                    //减25为状态栏的高度
                    wmParams.y = (int) event.getRawY() - loginButton.getMeasuredHeight() / 2 - 25;
                    //刷新
                    mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                    return true;
                }
                return false;  //此处必须返回false，否则OnClickListener获取不到监听
            }
        });
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isRunning) {
                    Toast("登陆程序运行中，请稍后！");
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            isRunning = true;
                            int times = 0;
                            String s = readText("/sdcard/zhangqing/peizhi/shuju.txt");
                            Model model = gson.fromJson(s, Model.class);
                            if (model == null) {
                                Toast("文件未找到或格式错误！");
                                return;
                            }
                            if (!TextUtils.isEmpty(model.getQQ())) {
                                String qq = model.getQQ();
                                String qqPwd = model.getQQPwd();
                                if (!TextUtils.isEmpty(qqPwd)) {
//                            RootShell.exec("pm clear com.tencent.mobileqq");
//                            Thread.sleep(2000);
                                    Intent intent = mContext.getPackageManager().getLaunchIntentForPackage("com.tencent.mobileqq");
                                    mContext.startActivity(intent);
                                    times = 0;
                                    while (true) {
                                        times++;
                                        if (times > 40) {
                                            throw new Exception();
                                        }
                                        String activity = getTopActivity();
                                        if (activity != null && activity.contains("com.tencent.mobileqq.activity.RegisterGuideActivity")) {
                                            break;
                                        }
                                        Thread.sleep(1000);
                                        //某些版本有开始动画
                                        RootShell.simulateTap(500, 30);
                                    }
                                    Thread.sleep(1000);
                                    RootShell.simulateTap(QQLoginButtonPoint);
                                    times = 0;
                                    while (true) {
                                        times++;
                                        if (times > 40) {
                                            throw new Exception();
                                        }
                                        String activity = getTopActivity();
                                        if (activity != null && activity.contains("com.tencent.mobileqq.activity.LoginActivity")) {
                                            break;
                                        }
                                        Thread.sleep(1000);
                                    }
                                    RootShell.simulateTap(QQLoginActivityUserPoint);
                                    RootShell.simulateText(qq);
                                    RootShell.simulateTap(QQLoginActivityPWDPoint);
                                    RootShell.simulateText(qqPwd);
                                    RootShell.simulateTap(QQLoginActivityLoginPoint);
                                    String activity;
                                    times = 0;
                                    while (true) {
                                        times++;
                                        if (times > 40) {
                                            throw new Exception();
                                        }
                                        activity = getTopActivity();
                                        if (activity != null && (activity.contains("com.tencent.mobileqq.activity.SplashActivity")
                                                || activity.contains("com.tencent.mobileqq.activity.VerifyCodeActivity"))) {
                                            break;
                                        }
                                        Thread.sleep(1000);
                                    }
                                    if (activity.contains("com.tencent.mobileqq.activity.SplashActivity")) {
                                        Toast("登录完成！");
                                    } else {
                                        isVer = true;
                                        verifyTimes = 0;
                                        VerifyCode(mContext);
                                    }
                                }
                            } else if (!TextUtils.isEmpty(model.getWeixin_email())) {
                                if (!TextUtils.isEmpty(model.getWeixinPasswd())) {
                                    Intent intent = mContext.getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
                                    mContext.startActivity(intent);
                                    Thread.sleep(3 * 1000);
                                    times = 0;
                                    while (true) {
                                        times++;
                                        if (times > 40) {
                                            throw new Exception();
                                        }
                                        String activity = getTopActivity();
                                        if (activity != null && activity.contains("com.tencent.mm.ui.account.mobile.MobileInputUI")) {
                                            break;
                                        }
                                        RootShell.simulateTap(WXLoginButtonPoint);
                                        Thread.sleep(1000);
                                    }
                                    Thread.sleep(2 * 1000);
                                    RootShell.simulateTap(WXPhoneLoginActivityUseOtherPoint);
                                    Thread.sleep(3 * 1000);
                                    times = 0;
                                    while (true) {
                                        times++;
                                        if (times > 40) {
                                            throw new Exception();
                                        }
                                        String activity = getTopActivity();
                                        if (activity != null && activity.contains("com.tencent.mm.ui.account.LoginUI")) {
                                            break;
                                        }
                                        RootShell.simulateTap(WXPhoneLoginActivityUseOtherPoint);
                                        Thread.sleep(1000);
                                    }
                                    RootShell.simulateTap(WXOtherLoginActivityUserPoint);
                                    RootShell.simulateText(model.getWeixin_email());
                                    RootShell.simulateTap(WXOtherLoginActivityPWDPoint);
                                    RootShell.simulateText(model.getWeixinPasswd());
                                    RootShell.simulateTap(WXOtherLoginActivityLoginPoint);
                                    Thread.sleep(3 * 1000);
                                    times = 0;
                                    while (true) {
                                        times++;
                                        if (times > 40) {
                                            throw new Exception();
                                        }
                                        String activity = getTopActivity();
                                        if (activity != null && !activity.contains("com.tencent.mm.ui.account.LoginUI")) {
                                            break;
                                        }
                                        RootShell.simulateTap(68, 923);
                                        Thread.sleep(1000);
                                    }
                                    Toast("微信操作完毕！");
                                }
                            } else if (!TextUtils.isEmpty(model.getPhone_line1number())) {
                                if (!TextUtils.isEmpty(model.getWeixinPasswd())) {
                                    Intent intent = mContext.getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
                                    mContext.startActivity(intent);
                                    Thread.sleep(3 * 1000);
                                    times = 0;
                                    while (true) {
                                        times++;
                                        if (times > 40) {
                                            throw new Exception();
                                        }
                                        String activity = getTopActivity();
                                        if (activity != null && activity.contains("com.tencent.mm.ui.account.mobile.MobileInputUI")) {
                                            break;
                                        }
                                        RootShell.simulateTap(WXLoginButtonPoint);
                                        Thread.sleep(1000);
                                    }
//                            RootShell.simulateTap(WXPhoneLoginActivityUserPoint);
//                            RootShell.simulateText(model.getPhone_line1number());
                                    RootShell.simulateTap(WXPhoneLoginActivityPWDPoint);
                                    RootShell.simulateText(model.getWeixinPasswd());
                                    RootShell.simulateTap(WXPhoneLoginActivityLoginPoint);
                                    Thread.sleep(3 * 1000);
                                    times = 0;
                                    while (true) {
                                        times++;
                                        if (times > 40) {
                                            throw new Exception();
                                        }
                                        String activity = getTopActivity();
                                        if (activity != null && !activity.contains("com.tencent.mm.ui.account.mobile.MobileInputUI")) {
                                            break;
                                        }
                                        RootShell.simulateTap(68, 923);
                                        Thread.sleep(1000);
                                    }
                                    Toast("微信操作完毕！");
                                }
                            } else {
                                Toast("没有QQ或微信账号信息！");
                            }
                            if (!isVer) {
                                isRunning = false;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Toast("程序发生了一些错误！");
                            isRunning = false;
                        }
                    }
                }).start();
            }
        });
        mWindowManager.addView(mFloatLayout, wmParams);
    }

    private void Toast(final String s) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, s, Toast.LENGTH_LONG).show();
            }
        });
    }

    private int verifyTimes = 0;

    private void VerifyCode(final Context mContext) {
        verifyTimes++;
        RootShell.screenCap();
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapUtil.corpBitmap(QQCodeActivityCodeStartPoint, QQCodeActivityCodeEndPoint);
        KeyUtil.CallBack callBack = new KeyUtil.CallBack() {
            @Override
            public void onFinish(String s) {
                try {
                    if (s != null) {
                        RootShell.simulateTap(QQCodeActivityEditPoint);
                        Thread.sleep(500);
                        RootShell.simulateText(s);
                        Thread.sleep(500);
                        RootShell.simulateTap(QQCodeActivityFinishPoint);
                        int times = 0;
                        while (true) {
                            times++;
                            if (times > 40) {
                                throw new Exception();
                            }
                            String activity = getTopActivity();
                            if (activity != null && activity.contains("com.tencent.mobileqq.activity.SplashActivity")) {
                                break;
                            }
                            Thread.sleep(1000);
                        }
                        Toast("登录完成！");
                        isRunning = false;
                    } else {
                        Toast("验证码获取失败！");
                        isRunning = false;
                    }
                } catch (Exception e) {
                    if (verifyTimes >= 3) {
                        isRunning = false;
                        Toast("程序发生了一些错误！");
                    } else {
                        VerifyCode(mContext);
                    }
                }
            }
        };
        if (SharedPreferenceUtil.getInstance().getDaMa() == 0) {
            KeyUtil.getLianZongKey(callBack);
        } else {
            KeyUtil.getYunMaKey(callBack);
        }
    }

    public void dismiss() {
        if (mWindowManager != null && mFloatLayout != null) {
            mWindowManager.removeView(mFloatLayout);
        }
    }

    public void toggleHome() {
        if (mFloatLayout == null) {
            return;
        }
        if (SharedPreferenceUtil.getInstance().getIsShowHome()) {
            mFloatLayout.findViewById(R.id.home_layout).setVisibility(View.VISIBLE);
        } else {
            mFloatLayout.findViewById(R.id.home_layout).setVisibility(View.GONE);
        }
    }

    private String readText(String path) throws Exception {
        FileInputStream fin = new FileInputStream(path);
        int length = fin.available();
        byte[] buffer = new byte[length];
        fin.read(buffer);
        fin.close();
        return new String(buffer, "UTF-8");
    }

    public String getTopActivity() {
        ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(2).get(0).topActivity;
        return cn.getClassName();
    }
}
